package com.lemo.juc;

public class Producer$ConsumerDemo1 {
	public static void main(String[] args) {
		Clerk1 clerk = new Clerk1();
		Producer1 producer = new Producer1(clerk);
		Consumer1 consumer = new Consumer1(clerk);

		new Thread(producer, "生产者A").start();

		new Thread(consumer, "消费者B").start();
		
		new Thread(producer, "生产者C").start();

		new Thread(consumer, "消费者D").start();
	}
}

class Clerk1 {
	private int product = 0;

	// 进货
	public synchronized void get() {
		while (product >= 1) {//防止虚假唤醒
			System.out.println("已满");

			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + ":" + ++product);
		this.notifyAll();

	}

	// 卖货
	public synchronized void sal() {
		while (product <= 0) {
			System.out.println("缺货");
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName() + ":" + --product);
		this.notifyAll();

	}
}

class Producer1 implements Runnable {
	private Clerk1 clerk;

	public Producer1() {
		super();
	}

	public Producer1(Clerk1 clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			clerk.get();
		}
	}

}

class Consumer1 implements Runnable {

	private Clerk1 clerk;

	public Consumer1(Clerk1 clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			clerk.sal();
		}
	}

}
